package com.foreknow.controller;

import com.foreknow.model.Admin;
import com.foreknow.service.AdminService;
import com.foreknow.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置服务器向客户端响应的内容的类型（MIME）
        //resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端请求的字符编码集为utf-8
        //req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //        out.println("--------------"+req.getMethod()); //获取客户端向服务器端的请求方法
        //        out.println("--------------"+req.getRequestURI()); //获取到URL的部分路径
        //        out.println("--------------"+req.getRequestURL()); //获取到请求路径
        //        out.println("--------------"+req.getServerPort()); //获取到服务器的端口号
        //        out.println("--------------"+req.getContextPath());//获取到Application Context的访问路径
        //如何获取到表单数据（也可以理解为获取请求参数）
        // http://localhost:8080/ManagerSystemWebProject/Login.html?username=tom@163.com&password=123456
        String name = req.getParameter("email");
        String password = req.getParameter("password");
        //调用Service层的方法
        AdminService service = new AdminServiceImpl();
        Admin admin = service.login(name,password);
        //可以将用户的信息保存到session中
        HttpSession session = req.getSession(); //获取HttpSession对象
        session.setAttribute("username",admin.getUsername());
        if(admin!=null) {
            //out.println(admin.getUsername()+"---"+admin.getPassword());
            //将请求转发给ManagerServlet
            req.getRequestDispatcher("manager?q=list").forward(req,resp);
        }else {
            out.println("error");
        }
    }
}
